package com.shigu.component.shiro.filter;

import com.alibaba.fastjson.JSON;
import com.shigu.component.enums.SessionEnum;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Service("wxOpeniidFilter")
public class WxOpeniidFilter implements Filter {

    private final Logger logger = Logger.getLogger(WxOpeniidFilter.class);
    @Value("${wechat.appid}")
    private String appId;
    @Value(("${wechat.appsecret}"))
    private String appSecret;
    @Value("${web_host}")
    private String webHost;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (!hasWxAuth()) {
            HttpServletRequest httpRequest= (HttpServletRequest) request;
            //获取请求头信息
//            Enumeration<String> headerNames = httpRequest.getHeaderNames();
//            Map<String,String> headerInfo = new HashMap<>();
//            while (headerNames.hasMoreElements()) {
//                String key =  headerNames.nextElement();
//                String value = httpRequest.getHeader(key);
//                headerInfo.put(key, value);
//            }
//            headerInfo.put("协议",request.getScheme());
//            logger.error(JSON.toJSONString(headerInfo));

            String url=httpRequest.getRequestURL().toString();
            String queryString=httpRequest.getQueryString();
            String backUrl= URLEncoder.encode(url+ (queryString==null?"":("?"+queryString)),
                                            "utf-8").replace("%","!");
            if(httpRequest.getRequestURI().contains(".json")) {
                backUrl=httpRequest.getHeader("Referer");
            }
            /*
            * 跳转授权页面 ，由微信重定向到 redirect_uri （wxlogin.htm）
            * state 放入 请求页面 backUrl 在wxlogin.htm 重定向跳转
            *  */
            String redirect="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId +
                    "&redirect_uri="+webHost+"wxlogin.htm&response_type=code&scope=snsapi_base" +
                    "&state="+ (StringUtils.isEmpty(backUrl)?"": URLEncoder.encode(backUrl,"utf-8"));
            if (!httpRequest.getRequestURI().contains(".json")) {
                HttpServletResponse httpServletResponse= (HttpServletResponse) response;
                httpServletResponse.sendRedirect(redirect);
            }else{
                writeToResponse((HttpServletResponse) response,"{\"success\":false,\"auth\":false,\"authUrl\":\""+ redirect +"\"}");
            }
            return;
        }
        chain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }

    /**
     * 登陆判断
     * @return
     * @throws IOException
     */
    public boolean hasWxAuth() throws IOException {
        Session session = SecurityUtils.getSubject().getSession();
        Object auth = session.getAttribute(SessionEnum.LOGIN_USER.toString());
        return auth!=null;
    }

    public void getHeaderInfo(Enumeration<String> headerNames){


    }

    public void writeToResponse(HttpServletResponse response,String jsonString){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");//修复post异常信息未被解析为json
        PrintWriter writer;
        try {
            writer = response.getWriter();
            writer.print(jsonString);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
